const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, userInfo } = event
  
  console.log('用户管理云函数调用:', { action, openid: wxContext.OPENID })
  
  try {
    switch (action) {
      case 'login':
        return await handleLogin(wxContext, userInfo)
      case 'getUserInfo':
        return await getUserInfo(wxContext.OPENID)
      case 'updateUserInfo':
        return await updateUserInfo(wxContext.OPENID, userInfo)
      case 'generateUserId':
        return await generateUserId()
      case 'debugUserInfo':
        return await debugUserInfo(wxContext.OPENID)
      case 'updateAvatar':
        return await updateAvatar(event, wxContext)
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('用户管理云函数错误:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 生成唯一用户ID
function generateUniqueUserId() {
  const timestamp = Date.now().toString(36) // 时间戳转36进制
  const randomStr = Math.random().toString(36).substring(2, 8) // 随机字符串
  return `USER_${timestamp}_${randomStr}`.toUpperCase()
}

// 生成9位数字用户ID
function generateNumericId() {
  // 生成9位数字ID，格式：1XXXXXXXX
  // 第一位固定为1，后8位为随机数字
  const timestamp = Date.now().toString().slice(-4) // 取时间戳后4位
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0') // 4位随机数
  return `1${timestamp}${random}`
}

// 生成用户编号（递增数字）- 保留用于兼容性
async function generateUserNumber() {
  try {
    // 获取当前最大用户编号
    const result = await db.collection('users')
      .orderBy('userNumber', 'desc')
      .limit(1)
      .get()
    
    let nextNumber = 1001 // 从1001开始编号
    
    if (result.data.length > 0 && result.data[0].userNumber) {
      nextNumber = result.data[0].userNumber + 1
    }
    
    return nextNumber
  } catch (error) {
    console.error('生成用户编号失败:', error)
    // 如果查询失败，使用时间戳作为备用方案
    return 1000 + Math.floor(Date.now() / 1000) % 10000
  }
}

// 检查9位数字ID是否已存在
async function checkNumericIdExists(numericId) {
  try {
    const result = await db.collection('users').where({
      numericId: numericId
    }).count()
    
    return result.total > 0
  } catch (error) {
    console.error('检查数字ID失败:', error)
    return false
  }
}

// 检查用户ID是否已存在
async function checkUserIdExists(userId) {
  try {
    const result = await db.collection('users').where({
      userId: userId
    }).count()
    
    return result.total > 0
  } catch (error) {
    console.error('检查用户ID失败:', error)
    return false
  }
}

// 生成用户ID（对外接口）
async function generateUserId() {
  let userId
  let numericId
  let attempts = 0
  const maxAttempts = 5
  
  // 确保生成的ID是唯一的
  do {
    userId = generateUniqueUserId()
    numericId = generateNumericId()
    attempts++
    
    if (attempts > maxAttempts) {
      throw new Error('生成唯一用户ID失败，请重试')
    }
  } while (await checkUserIdExists(userId) || await checkNumericIdExists(numericId))
  
  const userNumber = await generateUserNumber()
  
  return {
    success: true,
    userId: userId,
    numericId: numericId,
    userNumber: userNumber,
    displayId: `#${userNumber.toString().padStart(4, '0')}`
  }
}

// 处理用户登录
async function handleLogin(wxContext, userInfo) {
  const openid = wxContext.OPENID
  const unionid = wxContext.UNIONID
  
  console.log('处理用户登录:', { openid, unionid })
  
  try {
    // 查询用户是否已存在
    const userQuery = await db.collection('users').where({
      openid: openid
    }).get()
    
    const currentTime = new Date()
    
    if (userQuery.data.length > 0) {
      // 用户已存在，更新登录信息
      const existingUser = userQuery.data[0]
      console.log('用户已存在，更新登录信息:', existingUser._id)
      
      const updateData = {
        lastLoginTime: currentTime,
        loginCount: (existingUser.loginCount || 0) + 1
      }
      
      // 如果用户提供了新的头像或昵称，则更新
      if (userInfo && userInfo.nickName) {
        updateData.nickName = userInfo.nickName
      }
      if (userInfo && userInfo.avatarUrl) {
        updateData.avatarUrl = userInfo.avatarUrl
      }
      
      // 如果老用户没有userId或numericId，为其分配一个
      if (!existingUser.userId || !existingUser.numericId) {
        const idResult = await generateUserId()
        if (idResult.success) {
          updateData.userId = idResult.userId
          updateData.numericId = idResult.numericId
          updateData.userNumber = idResult.userNumber
          updateData.displayId = idResult.displayId
        }
      }
      
      await db.collection('users').doc(existingUser._id).update({
        data: updateData
      })
      
      // 返回更新后的用户信息
      const updatedUser = {
        ...existingUser,
        ...updateData
      }
      
      return {
        success: true,
        isNewUser: false,
        userInfo: {
          _id: updatedUser._id,
          userId: updatedUser.userId,
          numericId: updatedUser.numericId,
          userNumber: updatedUser.userNumber,
          displayId: updatedUser.displayId,
          openid: updatedUser.openid,
          unionid: updatedUser.unionid,
          nickName: updatedUser.nickName,
          avatarUrl: updatedUser.avatarUrl,
          gender: updatedUser.gender,
          country: updatedUser.country,
          province: updatedUser.province,
          city: updatedUser.city,
          createTime: updatedUser.createTime,
          lastLoginTime: updatedUser.lastLoginTime,
          loginCount: updatedUser.loginCount
        }
      }
    } else {
      // 新用户，创建用户记录
      console.log('新用户，创建用户记录')

      let userId, numericId, userNumber, displayId

      // 检查是否预设了用户ID信息
      if (userInfo?.userId && userInfo?.numericId) {
        console.log('使用预设的用户ID信息')
        userId = userInfo.userId
        numericId = userInfo.numericId
        userNumber = userInfo.userNumber
        displayId = userInfo.displayId
      } else {
        // 为新用户生成ID
        console.log('生成新的用户ID')
        const idResult = await generateUserId()
        if (!idResult.success) {
          throw new Error('生成用户ID失败')
        }
        userId = idResult.userId
        numericId = idResult.numericId
        userNumber = idResult.userNumber
        displayId = idResult.displayId
      }

      const newUser = {
        userId: userId,
        numericId: numericId,
        userNumber: userNumber,
        displayId: displayId,
        openid: openid,
        unionid: unionid,
        nickName: userInfo?.nickName || '微信用户',
        avatarUrl: userInfo?.avatarUrl || '',
        gender: userInfo?.gender || 0,
        country: userInfo?.country || '',
        province: userInfo?.province || '',
        city: userInfo?.city || '',
        createTime: currentTime,
        lastLoginTime: currentTime,
        loginCount: 1,
        status: 'active',
        level: 'normal', // 用户等级
        points: 0 // 积分
      }
      
      const createResult = await db.collection('users').add({
        data: newUser
      })
      
      console.log('用户创建成功:', createResult._id, '用户ID:', newUser.userId)
      
      return {
        success: true,
        isNewUser: true,
        userInfo: {
          ...newUser,
          _id: createResult._id
        }
      }
    }
  } catch (error) {
    console.error('登录处理错误:', error)
    throw error
  }
}

// 获取用户信息
async function getUserInfo(openid) {
  console.log('获取用户信息:', openid)
  
  const userQuery = await db.collection('users').where({
    openid: openid
  }).get()
  
  if (userQuery.data.length === 0) {
    return {
      success: false,
      error: '用户不存在'
    }
  }
  
  const user = userQuery.data[0]
  return {
    success: true,
    userInfo: {
      _id: user._id,
      userId: user.userId,
      numericId: user.numericId,
      userNumber: user.userNumber,
      displayId: user.displayId,
      openid: user.openid,
      unionid: user.unionid,
      nickName: user.nickName,
      avatarUrl: user.avatarUrl,
      gender: user.gender,
      country: user.country,
      province: user.province,
      city: user.city,
      createTime: user.createTime,
      lastLoginTime: user.lastLoginTime,
      loginCount: user.loginCount,
      level: user.level,
      points: user.points
    }
  }
}

// 更新用户信息
async function updateUserInfo(openid, userInfo) {
  console.log('更新用户信息:', { openid, userInfo })
  
  const userQuery = await db.collection('users').where({
    openid: openid
  }).get()
  
  if (userQuery.data.length === 0) {
    return {
      success: false,
      error: '用户不存在'
    }
  }
  
  const user = userQuery.data[0]
  const updateData = {
    updateTime: new Date()
  }
  
  // 只更新提供的字段
  if (userInfo.nickName !== undefined) {
    updateData.nickName = userInfo.nickName
  }
  if (userInfo.avatarUrl !== undefined) {
    updateData.avatarUrl = userInfo.avatarUrl
  }
  if (userInfo.gender !== undefined) {
    updateData.gender = userInfo.gender
  }
  if (userInfo.country !== undefined) {
    updateData.country = userInfo.country
  }
  if (userInfo.province !== undefined) {
    updateData.province = userInfo.province
  }
  if (userInfo.city !== undefined) {
    updateData.city = userInfo.city
  }
  if (userInfo.level !== undefined) {
    updateData.level = userInfo.level
  }
  if (userInfo.points !== undefined) {
    updateData.points = userInfo.points
  }
  
  await db.collection('users').doc(user._id).update({
    data: updateData
  })
  
  return {
    success: true,
    message: '用户信息更新成功'
  }
}

// 调试用户信息（包含详细的诊断信息）
async function debugUserInfo(openid) {
  console.log('调试用户信息:', openid)
  
  try {
    const userQuery = await db.collection('users').where({
      openid: openid
    }).get()
    
    const debugInfo = {
      openid: openid,
      userExists: userQuery.data.length > 0,
      userCount: userQuery.data.length,
      queryResult: userQuery.data
    }
    
    if (userQuery.data.length > 0) {
      const user = userQuery.data[0]
      debugInfo.userInfo = {
        _id: user._id,
        userId: user.userId || '❌ 未设置',
        numericId: user.numericId || '❌ 未设置',
        userNumber: user.userNumber || '❌ 未设置',
        displayId: user.displayId || '❌ 未设置',
        nickName: user.nickName || '❌ 未设置',
        openid: user.openid || '❌ 未设置',
        loginCount: user.loginCount || 0,
        createTime: user.createTime || '❌ 未设置',
        lastLoginTime: user.lastLoginTime || '❌ 未设置'
      }
      
      debugInfo.hasAllIds = !!(user.userId && user.numericId && user.userNumber && user.displayId)
    }
    
    // 检查用户总数
    const totalUsersResult = await db.collection('users').count()
    debugInfo.totalUsers = totalUsersResult.total
    
    console.log('用户调试信息:', debugInfo)
    
    return {
      success: true,
      debugInfo: debugInfo
    }
  } catch (error) {
    console.error('用户信息调试失败:', error)
    return {
      success: false,
      error: error.message || '调试失败'
    }
  }
}

// 更新用户头像
async function updateAvatar(event, wxContext) {
  const { userId, avatarUrl, avatarSource, updateTime } = event
  const openid = wxContext.OPENID

  console.log('🖼️ 更新用户头像:', { userId, avatarUrl, avatarSource, openid })

  if (!avatarUrl) {
    throw new Error('头像URL不能为空')
  }

  if (!openid) {
    console.error('🖼️ openid缺失，无法更新头像')
    throw new Error('用户身份信息缺失，请重新登录')
  }

  try {
    // 改进查找逻辑：优先使用openid查找，因为它是最可靠的标识
    let userQuery = await db.collection('users').where({
      openid: openid
    }).get()

    // 如果通过openid找不到，且提供了userId，尝试通过userId查找
    if (userQuery.data.length === 0 && userId) {
      console.log('🖼️ 通过openid未找到用户，尝试使用userId查找:', userId)
      userQuery = await db.collection('users').where({
        userId: userId
      }).get()
    }

    if (userQuery.data.length === 0) {
      console.error('🖼️ 用户不存在，openid:', openid, 'userId:', userId)
      
      // 提供更详细的错误信息
      const debugInfo = {
        openid: openid,
        userId: userId,
        timestamp: new Date().toISOString()
      }
      
      // 检查用户总数，用于调试
      const totalUsersResult = await db.collection('users').count()
      debugInfo.totalUsers = totalUsersResult.total
      
      console.log('🖼️ 调试信息:', debugInfo)
      throw new Error('用户不存在，可能是首次登录数据未同步完成，请稍后重试')
    }

    const user = userQuery.data[0]
    console.log('🖼️ 找到用户记录:', { _id: user._id, userId: user.userId, openid: user.openid })

    // 更新用户头像信息
    const updateResult = await db.collection('users').doc(user._id).update({
      data: {
        avatarUrl: avatarUrl,
        avatarSource: avatarSource || 'unknown',
        avatarUpdateTime: updateTime || new Date(),
        updateTime: new Date()
      }
    })

    console.log('✅ 用户头像更新成功:', updateResult)

    return {
      success: true,
      message: '头像更新成功',
      data: {
        userId: user.userId,
        avatarUrl: avatarUrl,
        avatarSource: avatarSource,
        updateTime: updateTime || new Date()
      }
    }

  } catch (error) {
    console.error('❌ 更新用户头像失败:', error)
    throw error
  }
}
